package com.dean.pokeking.repository

import android.content.Context
import android.util.Log
import com.dean.pokeking.MainApplication
import com.dean.pokeking.beans.LineupList
import com.dean.pokeking.beans.MonsterList
import com.dean.pokeking.beans.NpcInfo
import com.dean.pokeking.beans.PlayerList
import com.dean.pokeking.utils.FileUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * @ClassName TODO
 * @Description TODO
 * @Author Dean
 * @Date 2023/3/23
 * @Version 1.0
 */

class NpcDataRepository {

    private var npcList: List<NpcInfo> = emptyList()

    constructor() {}

    constructor(context: Context): this() {
        npcList = FileUtil.getAllNpcs("teams/小蛋队.txt", context)
    }

    suspend fun initData(teamName: String) =
        withContext(Dispatchers.IO) {
            npcList = FileUtil.readAllTeamFromExcel(MainApplication.getAppContext(), teamName)
        }

    suspend fun writeNpcPlayer(teamName: String, player: PlayerList) =
        withContext(Dispatchers.IO) {
            FileUtil.writeMonsterInfoToExcel(MainApplication.getAppContext(), player, teamName)
            npcList = FileUtil.readAllTeamFromExcel(MainApplication.getAppContext(), teamName)
        }

    suspend fun getAllTeamName(): List<String> =
        withContext(Dispatchers.IO) {
            FileUtil.getAllTeamName(MainApplication.getAppContext())
        }

    suspend fun getNpcLineupByNpcName(npcName: String): List<LineupList> =
        withContext(Dispatchers.IO) {
            npcList.find { it.result?.lineupList?.get(0)?.npc == npcName }
                ?.result?.lineupList ?: emptyList()
        }

    suspend fun savePlayerToExcel(teamName: String, player: PlayerList) =
        withContext(Dispatchers.IO) {
            FileUtil.writeMonsterInfoToExcel(MainApplication.getAppContext(), player, teamName)
        }

    suspend fun getNpcMonsterListByNpcName(npcName: String): List<MonsterList> =
        withContext(Dispatchers.IO) {
            npcList.find { it.result?.lineupList?.get(0)?.npc == npcName }
                ?.result?.monsterList ?: emptyList()
        }

    companion object {
        @Volatile
        private var instance: NpcDataRepository? = null

        fun getInstance() =
            instance ?: synchronized(this) {
                instance ?: NpcDataRepository().also { instance = it }
            }

        fun getInstance(context: Context) =
            instance ?: synchronized(this) {
                instance ?: NpcDataRepository(context).also { instance = it }
            }
    }

}